package com.rv.admin.helper;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.stp.StpUtil;
import com.rv.admin.domain.User;

/**
 * @author sundez
 * @version 1.1.3.9
 * @since 2025/7/31
 */
public class LoginHelper {

    public static final String JOIN_CODE = ":";
    public static final String LOGIN_USER_KEY = "loginUser";

    /**
     * 登录系统
     *
     * @param user 登录用户信息
     */
    public static void login(User user) {
        SaHolder.getStorage().set(LOGIN_USER_KEY, user);
        StpUtil.login(user.getId());
        setLoginUser(user);
    }


    /**
     * 设置用户数据(多级缓存)
     */
    public static void setLoginUser(User user) {
        StpUtil.getTokenSession().set(LOGIN_USER_KEY, user);
    }

    /**
     * 获取用户(多级缓存)
     */
    public static User getLoginUser() {
        User loginUser = (User) SaHolder.getStorage().get(LOGIN_USER_KEY);
        if (loginUser != null) {
            return loginUser;
        }
        loginUser = (User) StpUtil.getTokenSession().get(LOGIN_USER_KEY);
        SaHolder.getStorage().set(LOGIN_USER_KEY, loginUser);
        return loginUser;
    }

    /**
     * 获取用户id
     */
    public static Long getUserId() {
        User loginUser = getLoginUser();
        return loginUser.getId();
    }

    /**
     * 获取用户账户
     */
    public static String getUsername() {
        return getLoginUser().getUsername();
    }

}
